package com.gowants.pems.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.gowants.pems.aspect.Importance;
import com.gowants.pems.aspect.OperType;
import com.gowants.pems.aspect.ScmsAopLog;
import com.gowants.pems.config.AccessLimit;
import com.gowants.pems.mapper.ParamsMapper;
import com.gowants.pems.mapper.SysUserMapper;
import com.gowants.pems.model.*;
import com.gowants.pems.service.*;
import com.gowants.pems.util.*;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping(value = "/sysUser/")
public class SysUserController extends BaseController {

	@Autowired
	private SysUserService scmsUserService;
	@Autowired
	private SysPowerService ScmsPowerService;
	@Autowired
	private SysUserMapper userMapper;
	@Autowired
	private ParamsMapper paramsMapper;
	@Autowired
	private RedisUtils redisUtils;
	@Autowired
	private SysPermissionService sysPermissionService;
	
	/**
	 * 
	 * <获取用户列表>
	 * 
	 * @param page  查询的页码
	 * @param limit 查询条数
	 * @Param request 请求对象,用于封装返回信息使用
	 * @return
	 * @remake
	 */
	@RequestMapping(value = "getList", method = RequestMethod.POST)
	@AccessLimit(seconds = 1, maxCount = 3) // 1秒内 允许请求3次
	@ScmsAopLog(description = "用户列表查看", opType = OperType.execute, importance = Importance.commonly)
	public JSONMap getList(@RequestParam(defaultValue = "1", required = false, value = "page") int page,
			@RequestParam(defaultValue = "10", required = false, value = "limit") int limit,
			@RequestParam(defaultValue = "", required = false, value = "reqData") String reqData,
			HttpServletRequest req) {
		try {
			if (!isPower("/sysUser/getList.do")) {
				return doResponse(req, "TSMS_0000228");
			}
			JSONMap resultMap = new JSONMap();
			SysUser record = new SysUser();

			if (!"".equals(reqData)) {
				JSONList jsonCondition = getCondition(reqData);
				for (Object cond : jsonCondition) {
					buildConditionnew(cond, record);
				}
			}
			// 设置分页查询信息
			PageHelper.startPage(page, limit);

			List<SysUser> SysLogList = this.scmsUserService.select(record);
			PageInfo<SysUser> pageInfo = new PageInfo<SysUser>(SysLogList);

			pageSetData(req, resultMap, page, limit, pageInfo.getPages(), "", SysLogList, pageInfo.getTotal());

			return doResponse(req, "", resultMap);
		} catch (Exception e) {
			return doResponse(req, e.getMessage());
		}
	}

	/**
	 * 
	 * <构建查询条件>
	 * 
	 * @param cond
	 * @param record
	 * @remake
	 */
	private void buildConditionnew(Object cond, SysUser record) {
		JSONMap condition = JSONMap.parseJSONMap(cond.toString());
		if (!this.ckeckBlankKeyWord(condition)) {
			return;
		}
		String field = condition.getString("field");
		String keyword = condition.getString("keyword");

		if (StringUtils.isNotEmpty(field) && StringUtils.isNotEmpty(keyword)) {
			switch (field) {
			case "name":
				record.setName(keyword);
				break;
			case "type":
				record.setType(Integer.parseInt(keyword));
				break;
			case "state":
				record.setState(Integer.parseInt(keyword));
				break;
			case "createUid":
				record.setCreateUid(keyword);
				break;
			case "startTime":
				record.setStartTime(DateUtil.dateFormat(keyword));
				break;
			case "endTime":
				record.setEndTime(DateUtil.dateFormat(keyword));
				break;
			case "userName":
				record.setUserName(keyword);
				break;
			case "phone":
				record.setPhone(keyword);
				break;
			case "role":
				record.setRole(keyword);
				break;
			case "departmentId":
				record.setDepartmentId(keyword);
				break;
			case "isBlackList":
				record.setIsBlackList(Integer.parseInt(keyword));
				break;
			}
		}
	}

	/**
	 * 
	 * <空字段校验>
	 * 
	 * @param condition
	 * @return
	 * @remake
	 */
	private boolean ckeckBlankKeyWord(JSONMap condition) {

		if (StringUtils.isBlank(condition.getString("keyword"))) {
			return false;
		}

		return true;
	}

	@RequestMapping(value = "save")
	@AccessLimit(seconds = 1, maxCount = 3) // 1秒内 允许请求3次
	@ScmsAopLog(description = "用户添加", opType = OperType.execute, importance = Importance.commonly)
	public JSONMap save(String request, HttpServletRequest req) {
		String code = "TSMS_0000036";
		try {
			if (!isPower("/sysUser/save.do")) {
				return doResponse(req, "TSMS_0000228");
			}
			SysUser record = getRequestBody(request, SysUser.class);
			record.setCreateTime(DateUtil.getDate());
			record.setCreateUid(getUserId());
			record.setId(UUID.randomUUID().toString());
			record.setIsBlackList(0);
			String codes = scmsUserService.saveCheck(record);
			if (StringUtils.isNotBlank(codes)) {
				return doResponse(req, codes, null);
			}
			record.setPwd(MD5.md5(record.getPwd()));
			record.setIsBlackList(0);
			int i = scmsUserService.save(record);
			if (i > 0) {
				code = "TSMS_0000001";
			}
			return doResponse(req, code, null);
		} catch (Exception e) {
			return doResponse(req, e.getMessage(), null);
		}
	}

	@RequestMapping(value = "update")
	@AccessLimit(seconds = 1, maxCount = 3) // 1秒内 允许请求3次
	@ScmsAopLog(description = "用户修改", opType = OperType.execute, importance = Importance.commonly)
	public JSONMap update(String request, HttpServletRequest req) {
		String code = "TSMS_0000047";
		try {
			if (!isPower("/sysUser/update.do")) {
				return doResponse(req, "TSMS_0000228");
			}
			SysUser record = getRequestBody(request, SysUser.class);

			String codes = scmsUserService.saveCheck(record);
			if (StringUtils.isNotBlank(codes)) {
				return doResponse(req, codes, null);
			}
			SysUser scmsUser = scmsUserService.selectOne(record.getId());
			if (null != scmsUser) {
				if (scmsUser.getPwd().equals(record.getPwd())) {
					record.setPwd(null);
				} else {
					record.setPwd(MD5.md5(record.getPwd()));
				}
			}
			int i = scmsUserService.update(record);
			if (i > 0) {
				code = "TSMS_0000002";
			}
			return doResponse(req, code, null);

		} catch (Exception e) {
			return doResponse(req, e.getMessage(), null);
		}
	}

	/**
	 * 
	 * <删除>
	 * 
	 * @param         request={"id":"d16f1273-1678-4d66-96c6-746955327d51"}
	 * @param request 请求对象
	 * @return
	 * @remake
	 */
	@RequestMapping(value = "delete")
	@AccessLimit(seconds = 1, maxCount = 3) // 1秒内 允许请求3次
	@ScmsAopLog(description = "用户删除", opType = OperType.execute, importance = Importance.important)
	public JSONMap delete(String request, HttpServletRequest req) {
		try {
			if (!isPower("/sysUser/delete.do")) {
				return doResponse(req, "TSMS_0000228");
			}
			String code = "TSMS_0000048";

			// 参数对象
			JSONMap requestBody = getRequestBody(request);
			String id = requestBody.getString("id");

			if ("".equals(id) || null == id) {
				code = "TSMS_0000205";
				return doResponse(req, code, null);

			}

			int executeNum = scmsUserService.delete(id);// 删除 审核信息 及 上传文件
			if (executeNum > 0) {
				code = "TSMS_0000050";
			}
			return doResponse(req, code, null);
		} catch (Exception e) {
			return doResponse(req, e.getMessage(), null);
		}

	}

	/**
	 * 根据id获取本条数据
	 * 
	 * @param request
	 * @param req
	 * @return
	 */
	@RequestMapping(value = "selectOne")
	@AccessLimit(seconds = 1, maxCount = 3) // 1秒内 允许请求3次
	@ScmsAopLog(description = "用户查看", opType = OperType.execute, importance = Importance.commonly)
	public JSONMap selectOne(String request, HttpServletRequest req) {
		String code = "";
		try {
			// 参数对象
			JSONMap requestBody = getRequestBody(request);
			String id = requestBody.getString("id");
			if ("".equals(id) || null == id) {
				code = "TSMS_0000205";
				return doResponse(req, code, null);
			}
			SysUser scmsUser = scmsUserService.selectOne(id);
			return doResponse(req, code, scmsUser);
		} catch (Exception e) {
			code = e.getMessage();
			return doResponse(req, code, null);
		}

	}

	@RequestMapping("getMyAllInfo")
	@AccessLimit(seconds = 1, maxCount = 3) // 1秒内 允许请求3次
	@ScmsAopLog(description = "用户获取个人信息", opType = OperType.execute, importance = Importance.important)
	public JSONMap getMyAllInfo(HttpServletRequest req) {
		String code = "";
		try {
			SysUser scmsUser = scmsUserService.selectOne(getUserId());
			return doResponse(req, code, scmsUser);
		} catch (Exception e) {
			code = e.getMessage();
			return doResponse(req, code, null);
		}

	}

	@RequestMapping(value = "uploadImage")
	@AccessLimit(seconds = 1, maxCount = 3) // 1秒内 允许请求3次
	@ScmsAopLog(description = "用户图片上传", opType = OperType.execute, importance = Importance.important)
	public JSONMap uploadImage(MultipartFile myFile, HttpServletRequest req) {
		String code = "";
		try {

			// 校验上传文件
			int checkResult = scmsUserService.uploadCheck(myFile, Const.sys_user_type, Const.sys_user_size);

			// 文件超出限制大小
			if (checkResult == -1) {
				return doResponse(req, "TSMS_0000025");
			}

			// 文件格式不对
			if (checkResult == 0) {
				return doResponse(req, "TSMS_0000026");
			}
			String path = scmsUserService.uploadNew(myFile, Const.sys_user_path, null, Const.sys_user_mapping, true,
					true);
			if ("xxxxxxxxxx".equals(path)) {
				return doResponse(req, "TSMS_0000257");
			} else if ("".equals(path)) {
				return doResponse(req, "TSMS_0000089");
			}
			JSONMap resultMap = new JSONMap();
			resultMap.put("path", path);
			return doResponse(req, code, resultMap);

		} catch (Exception e) {
			code = e.getMessage();
			return doResponse(req, code, null);
		}
	}

	@RequestMapping(value = "updatePwd")
	@AccessLimit(seconds = 1, maxCount = 3) // 1秒内 允许请求3次
	@ScmsAopLog(description = "用户修改密码", opType = OperType.execute, importance = Importance.important)
	public JSONMap updatePwd(String request, HttpServletRequest req) {
		String code = "";
		JSONMap requestBody = getRequestBody(request);
		String oldPwd = requestBody.getString("oldPwd");
		String newPwd = requestBody.getString("newPwd");
		SysUser user = new SysUser();
		user.setPwd(MD5.md5(oldPwd));
		user.setId(getUserId());

		List<SysUser> userList = scmsUserService.select(user);
		if (userList.size() < 1) {
			code = "TSMS_0000136";
			return doResponse(req, code, null);
		}
		SysUser record = new SysUser();
		record.setPwd(MD5.md5(newPwd));
		record.setId(getUserId());
		int executeNum = this.scmsUserService.update(record);
		if (executeNum > 0) {

			code = "TSMS_0000138";
			return doResponse(req, code, null);
		} else {
			code = "TSMS_0000137";
			return doResponse(req, code, null);
		}

	}

	@RequestMapping(value = "updateState")
	@AccessLimit(seconds = 1, maxCount = 3) // 1秒内 允许请求3次
	@ScmsAopLog(description = "用户账号冻结、激活修改", opType = OperType.execute, importance = Importance.important)
	public JSONMap updateState(String request, HttpServletRequest req) {
		String code = "TSMS_0000047";
		try {
			JSONMap requestBody = getRequestBody(request);
			String id = requestBody.getString("id");
			SysUser record = new SysUser();
			SysUser scmsUser = scmsUserService.selectOne(id);
			if (0 == scmsUser.getState()) {
				// 冻结
				record.setState(1);
				record.setId(id);
				int executeNum = this.scmsUserService.update(record);
				if (executeNum > 0) {
					code = "TSMS_0000331";// 冻结成功
				} else {
					code = "TSMS_0000332";
				}
			} else {
				record.setState(0);
				record.setId(id);
				int executeNum = this.scmsUserService.update(record);
				if (executeNum > 0) {
					code = "TSMS_0000333";// 激活成功
				} else {
					code = "TSMS_0000334";
				}
			}
			return doResponse(req, code, null);

		} catch (Exception e) {
			code = e.getMessage();
			return doResponse(req, code, null);
		}
	}

	/**
	 * 获取个人一级权限
	 * 
	 * @return
	 */
	@RequestMapping(value = "getMyOnePower")
	@AccessLimit(seconds = 1, maxCount = 10) // 1秒内 允许请求3次
	@ScmsAopLog(description = "获取个人一级权限", opType = OperType.execute, importance = Importance.commonly)
	public JSONMap getMyOnePower(String request, HttpServletRequest req) {
		String code = "";
		try {
			SysUser userInfo = getUser();
			if (userInfo == null) {
				code = "TSMS_0000261";
				return doResponse(req, code, null);
			}
			JSONList list1 = new JSONList();
			// 首先先把一级模块
			SysPower record = new SysPower();
			record.setPid("10001");
			record.setIsenable(1);
			record.setRoleId(userInfo.getRole());
			if (StringUtils.isBlank(userInfo.getRole())) {
				return doResponse(req, code, null);
			}
			record.setType(0);
			List<SysPower> list = ScmsPowerService.select(record);
			for (SysPower fps : list) {
				JSONMap responses0 = new JSONMap();
				responses0.put("permissionId", fps.getPermissionId());
				responses0.put("name", fps.getName());
				responses0.put("pid", fps.getPid());
				responses0.put("url", fps.getUrl());
				responses0.put("icon", fps.getIcon());
				responses0.put("iconZh", fps.getIconZh());
				responses0.put("backgroundColor", fps.getBackgroundColor());
				list1.add(responses0);
			}

			return doResponse(req, code, list1);

		} catch (Exception e) {
			code = e.getMessage();
			return doResponse(req, code, null);
		}

	}
	/**
	 * 获取个人二级权限
	 * 
	 * @return
	 */
	@RequestMapping(value = "getMyTwoPower")
	@AccessLimit(seconds = 1, maxCount = 10) // 1秒内 允许请求3次
	@ScmsAopLog(description = "获取个人二级权限", opType = OperType.execute, importance = Importance.commonly)
	public JSONMap getMyTwoPower(String request, HttpServletRequest req) {
		String code = "";
		try {
			SysUser userInfo = getUser();
			if (userInfo == null) {
				code = "TSMS_0000261";
				return doResponse(req, code, null);
			}
			JSONMap responses = new JSONMap();
			JSONMap requestBody = getRequestBody(request);
			String permissionId = requestBody.getString("permissionId");
			SysPower fp = new SysPower();
			fp.setType(0);
			String role = "";
			if (StringUtils.isBlank(userInfo.getRole())) {
				return doResponse(req, code, null);
			}
			if (null != userInfo.getRole()) {
				role = userInfo.getRole();
			}
			fp.setRoleId(role);
			fp.setIsenable(1);
			fp.setPid(permissionId);
			List<SysPower> powerList = ScmsPowerService.select(fp);
			responses.put("powerList", powerList);
			SysPermission sysp=sysPermissionService.selectOne(permissionId);
			responses.put("permission", sysp);
			return doResponse(req, code, responses);

		} catch (Exception e) {
			code = e.getMessage();
			return doResponse(req, code, null);
		}

	}
	/**
	 * 获取个人三四级权限
	 * 
	 * @return
	 */
	@RequestMapping(value = "getMyThreePower")
	@AccessLimit(seconds = 1, maxCount = 10) // 1秒内 允许请求3次
	@ScmsAopLog(description = "获取个人三四级权限", opType = OperType.execute, importance = Importance.commonly)
	public JSONMap getMyThreePower(String request, HttpServletRequest req) {
		String code = "";
		try {
			SysUser userInfo = getUser();
			if (userInfo == null) {
				code = "TSMS_0000261";
				return doResponse(req, code, null);
			}
			JSONList list1 = new JSONList();
			JSONMap requestBody = getRequestBody(request);
			String permissionId = requestBody.getString("permissionId");
			SysPower fp = new SysPower();
			fp.setType(0);
			String role = "";
			if (StringUtils.isBlank(userInfo.getRole())) {
				return doResponse(req, code, null);
			}
			if (null != userInfo.getRole()) {
				role = userInfo.getRole();
			}
			fp.setRoleId(role);
			fp.setIsenable(1);
			List<SysPower> fpmsPower = ScmsPowerService.select(fp);
			// 先取本级
			for (int i = 0; i < fpmsPower.size(); i++) {
				if (permissionId.equals(fpmsPower.get(i).getPid())) {
					JSONMap responses1 = new JSONMap();
					responses1.put("permissionId", fpmsPower.get(i).getPermissionId());
					responses1.put("name", fpmsPower.get(i).getName());
					responses1.put("pid", fpmsPower.get(i).getPid());
					responses1.put("url", fpmsPower.get(i).getUrl());
					responses1.put("icon", fpmsPower.get(i).getIcon());
					responses1.put("iconZh", fpmsPower.get(i).getIconZh());
					responses1.put("backgroundColor", fpmsPower.get(i).getBackgroundColor());
					responses1.put("remarks", fpmsPower.get(i).getRemarks());
					JSONList list3 = new JSONList();
					for (int y = 0; y < fpmsPower.size(); y++) {
						if (fpmsPower.get(i).getPermissionId().equals(fpmsPower.get(y).getPid())) {
							JSONMap responses2 = new JSONMap();
							responses2.put("permissionId", fpmsPower.get(y).getPermissionId());
							responses2.put("name", fpmsPower.get(y).getName());
							responses2.put("pid", fpmsPower.get(y).getPid());
							responses2.put("url", fpmsPower.get(y).getUrl());
							responses2.put("icon", fpmsPower.get(y).getIcon());
							responses2.put("iconZh", fpmsPower.get(y).getIconZh());
							responses2.put("backgroundColor", fpmsPower.get(y).getBackgroundColor());
							responses2.put("remarks", fpmsPower.get(y).getRemarks());
							list3.add(responses2);
//								fpmsPower.remove(y);
//								y--;
						}
					}
//						fpmsPower.remove(i);
//						i--;
					responses1.put("children", list3);
					list1.add(responses1);
				}
			}
			return doResponse(req, code, list1);

		} catch (Exception e) {
			code = e.getMessage();
			return doResponse(req, code, null);
		}

	}
	/**
	 * 加入黑名单
	 * 
	 * @param request
	 * @param req
	 * @return
	 */
	@RequestMapping("addBlackList")
	@AccessLimit(seconds = 1, maxCount = 3) // 1秒内 允许请求3次
	public JSONMap addBlackList(String request, HttpServletRequest req) {
		String code = "";
		try {
			// 参数对象
			List<String> list = new ArrayList<>();
			List<JSONObject> jlist = JSONObject.parseArray(request, JSONObject.class);
			for (JSONObject jbt : jlist) {
				list.add(jbt.getString("id"));
			}
			userMapper.addBlackList(list);
			return doResponse(req, code, null);
		} catch (Exception e) {
			code = e.getMessage();
			return doResponse(req, code, null);
		}
	}

	/**
	 * 解除黑名单
	 * 
	 * @param request
	 * @param req
	 * @return
	 */
	@RequestMapping("removeBlackList")
	@AccessLimit(seconds = 1, maxCount = 3) // 1秒内 允许请求3次
	public JSONMap removeBlackList(String request, HttpServletRequest req) {
		String code = "";
		try {
			// 参数对象
			JSONMap requestBody = getRequestBody(request);
			String id = requestBody.getString("id");
			userMapper.removeBlackList(id);
			return doResponse(req, code, null);
		} catch (Exception e) {
			code = e.getMessage();
			return doResponse(req, code, null);
		}
	}

	

}
